import imaplib
import email
import os
from email.header import decode_header

def receive_attachments(
    IMAP_server: str = "imap.yn.chinamobile.com",
    receiver_mail: str = "zhangxiaoming@yn.chinamobile.com",
    #邮箱授权码
    receiver_password: str = "33D07A9F3435D0C30700",
    # receive_path: str = "D:\\Code\\python\\DigitalRobots\\wx\\email_files",
    receive_path: str = "./email_files",
    subject_filter: str = None
):
    # 创建IMAP4类的实例
    mail = imaplib.IMAP4_SSL(IMAP_server)
    # 登录邮箱
    mail.login(receiver_mail, receiver_password)
    # 选择收件箱
    mail.select("inbox")

    # 搜索指定主题的邮件
    if subject_filter:
        # 对主题进行UTF-8编码
        subject_filter_encoded = f'(SUBJECT "{subject_filter}")'.encode('utf-8')
        status, messages = mail.search(None, subject_filter_encoded)
    else:
        status, messages = mail.search(None, "ALL")

    # 转换邮件ID列表
    mail_ids = messages[0].split()

    for mail_id in mail_ids:
        # 获取邮件内容
        status, msg_data = mail.fetch(mail_id, "(RFC822)")
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_bytes(response_part[1])
                # 解码邮件主题
                subject, encoding = decode_header(msg["Subject"])[0]
                if isinstance(subject, bytes):
                    subject = subject.decode(encoding if encoding else "utf-8")

                # 检查邮件是否有附件
                if msg.is_multipart():
                    for part in msg.walk():
                        content_type = part.get_content_type()
                        content_disposition = str(part.get("Content-Disposition"))
                        try:
                            # 解码文件名
                            filename = part.get_filename()
                            if filename:
                                filename = decode_header(filename)[0][0]
                                if isinstance(filename, bytes):
                                    filename = filename.decode('utf-8')
                                if content_disposition and "attachment" in content_disposition:
                                    # 创建下载路径
                                    if not os.path.exists(receive_path):
                                        os.makedirs(receive_path)
                                    filepath = os.path.join(receive_path, filename)
                                    # 写入文件
                                    with open(filepath, "wb") as f:
                                        f.write(part.get_payload(decode=True))
                                    print(f"附件已保存: {filepath}")
                        except Exception as e:
                            print(f"下载附件失败: {e}")

    # 关闭连接
    mail.close()
    mail.logout()

# 调用函数并传入subject_filter参数
receive_attachments(subject_filter="市场部通报")
